/**
 * 公共请求http封装
 * @method httpRequest
 * @for 所属类名没有
 * @param httpRequest({
	url: '请求路径', //字符串
	method: 'get/post', //字符串
	data: {}, //对象
	callback:function(){} //方法
 })
 * @return 没有
 */

import configure from '../configure/server/index.js'
import { userInfoKey } from "./../constant/index.js"
import { showLoading,showErrMsg } from "./msg.js"

export function httpReq(config){
	let backServer = config.backServer || configure.server.backServer;
	let { url,method,data,loading,errorText,noCheckLogin } = config;
	data = data || {};
	
	return new Promise((resolve,reject)=>{
		if(loading != 'none'){
			showLoading();
		}
		
		// 检测登录
		if(!noCheckLogin){
			uni.getStorage({
				key: userInfoKey,
				success: function (res) {
					let { userid } = res.data;
					
					uni.request({
						url: backServer + url, //仅为示例，并非真实接口地址。
						method: method,
						header: {
							'userid': userid
						},
						data,
						success: (res) => {
							
							let data = res.data;
							
							uni.hideLoading();
												
							if (data.code == 200) {
								resolve(data);
							}else{
								showErrMsg(data.msg || errorText);
							}
							
						},
						fail:function(err){
								
							uni.hideLoading();
							
							showErrMsg(errorText);
						
						}
					});
				
				}, 
				fail:function(){
					uni.hideLoading();
					uni.navigateTo({url:`/pages/login/login`})
				}
			});
		}else{
			uni.request({
				url: backServer + url, //仅为示例，并非真实接口地址。
				method: method,
				header: {
					'userid': ''
				},
				data,
				success: (res) => {
					
					let data = res.data;
					
					uni.hideLoading();
										
					if (data.code == 200) {
						resolve(data);
					}else{
						showErrMsg(data.msg || errorText);
					}
					
				},
				fail:function(err){
						
					uni.hideLoading();
					
					showErrMsg(errorText);
				
				}
			});
		}
		
	})
	
}

